<template>
	<view>
		<up-image :src="options.activityBgImage || bg" width="100vw" height="100vh" mode="widthFix"></up-image>
		
		<view class="countdown" v-if="options.activityStatus !== '0'">
			<up-count-down :time="10 * 1000" format="sss后进入活动" @change="changeCountDown"></up-count-down>
		</view>
		<view class="op-wrap">
			<up-button type="warning" text="参与活动" shape="circle" @click="handleClick"></up-button>
		</view>
	</view>
	
	<up-modal :show="show">
		<view class="form">
			<view class="item-label">姓名</view>
			
			<up-input
				:readonly="!available"
				placeholder=""
				border="surround"
				v-model="userInfo.realName"
			></up-input>
			
			<view class="item-label">手机</view>
			<view style="display: flex;align-items: center;" v-if="!userInfo.mobile">
				<up-input
					placeholder="请使用绑定微信手机号"
					placeholderStyle="font-size:12px;"
					border="surround"
					v-model="userInfo.mobile"
					readonly
				></up-input>
				<button size="mini" class="phone-btn"
				open-type="getPhoneNumber"
				@getphonenumber="getPhoneNumber" v-if="!isH5">授权</button>
			</view>
			<up-input
				placeholder="请使用绑定微信手机号"
				placeholderStyle="font-size:12px;"
				border="surround"
				v-model="userInfo.mobile"
				readonly
				v-if="userInfo.mobile"
			></up-input>
			<view class="item-label">单位</view>
			<up-input
				v-if="available"
				readonly
				placeholder=""
				border="surround"
				v-model="userInfo.orgName"
				@tap="showPicker=true"
			></up-input>
			<up-input
				v-if="!available"
				readonly
				placeholder=""
				border="surround"
				v-model="userInfo.orgName"
			></up-input>
			
			
		</view>
		<template v-slot:confirmButton>
			<view class="signup" @click="handleTourist">
				提交
			</view>
		</template>
	</up-modal>
	
	<up-action-sheet
		style="background-color: #fff;"
		class="sheet-view"
		:show="showPicker"
		:actions="orgList"
		title="请选择单位"
		@close="showPicker = false"
		@select="confirm"
	>
	</up-action-sheet>
</template>

<script>
	import { activityApi } from '@/api/activity/activity-app.js';
	import { userApi } from '@/api/user/user-api.js';
	import { loginApi } from '@/api/login/login-api'
	import { wxLogin,errorToast  } from '@/utils/common'; 
	
	export default {
		data() {
			return {
				show: false,
				bg: 'https://jqgh-public.yqfoodec.com/20250411/bg_64878.jpg',
				options: {
					id: ''
				},
				available:true,
				userInfo: {
					briskWalkId: '',
					memberId: '',
					realName: '',
					mobile: '',
					orgName: '',
					orgId: '',
				},
				//orgName: this.$store.state.user.orgName,
				params: {
					page: 1,
					limit: 1000
				},
				//loginUserMobile: this.$store.state.user.mobile,
				orgList: [],
				showPicker: false,
				regParams:{},
				loginParams:{},
				isH5:false,
			}
		},
		onLoad(options) { // options.activityStatus 0 未开始  1 活动中  2  已结束
			let userInfo = uni.getStorageSync('userInfo')
			if (userInfo) {
				this.userInfo = userInfo
				if(userInfo.orgId){
					this.available = false;
				}
			}
			let scene = decodeURIComponent(options.scene)
			if (scene !== 'undefined') { // 小程序扫码过来的scene
				// console.log(scene.slice(3)) // id=16
				const id = scene.slice(3)
				// console.log(id)
				// if (userInfo) { // 已登录就直接跳转
				// 	uni.redirectTo({
				// 		url: `/brisk-walking/detail?title=健步走&id=${id}`
				// 	})
				// } else {
					this.options.title = '健步走'
					this.options.id = id
					this.getJoinList(id)
				// }
				
			} else { //console.log(options)
				this.options = options
				if (options.joinOrgId) {
					this.origList(options.joinOrgId)
				} else {
					this.getJoinList(options.id)
				}
				
			}
			
		},
		methods: {
			// 扫码过来的获取可参与的组织数组 
			async getJoinList(id){
				const result = await userApi.getJoinOrgList(id);
				this.options.activityBgImage = result.data.bgImg
				this.origList(result.data.orgIdList)
			},
			async origList(joinOrgId) {
				const result = await userApi.getOrgList();
				let dataList = [];
				for (var i = 0; i < result.data.length; i++) {
					const item = result.data[i];
					item.name = item.unionAbbreviation;
					dataList.push(item);
				}
				let filterOrg = dataList.filter(item => joinOrgId.includes(item.id));
				this.orgList = filterOrg;
				
			},
			confirm(e) {
				let data = JSON.parse(JSON.stringify(e))
		
				this.userInfo.orgName = data.unionAbbreviation;
				this.userInfo.orgId = data.id;
			},
			async handleClick() {
				// #ifdef H5
				await this.initFormData();
				// #endif
				let userInfo = uni.getStorageSync('userInfo')
				if (this.userInfo.orgId) {
					this.handleRedirect()
				} else {
					if (this.options.activityStatus !== '0') {
						this.show = true
					} else {
						errorToast('活动未开始');
					}
					
				}
			},
			async handleRedirect() {
				// 参与活动
				const result = await activityApi.getActivityJoin(this.options.id);
				
				if (result.code == 0) {
					uni.redirectTo({
						url: `/brisk-walking/detail?title=${this.options.title}&id=${this.options.id}`
					})
				}
				
			},
			// 游客用户参与活动 getTouristJoin
			async handleTourist() {
				 const { realName, mobile, orgName, orgId, memberId } = this.userInfo;
				if(!realName){
					errorToast('请输入姓名');
					return;
				}
				if(!mobile){
					errorToast('请输入手机号');
					return;
				}
				if(!orgName){
					errorToast('请选择单位');
					return;
				}
				let params = {
				  "briskWalkId": this.options.id,
				  "realName": realName,
				  "mobile": mobile,
				  "orgId": orgId
				}
				
				try{
					// 更新会员信息
					await loginApi.updateUserInfo({ id: memberId, realName, orgId });
					//获取更新后的会员信息
					const userData = await loginApi.getUserInfoByMobile({mobile:mobile});
					// 更新登陆信息,更新 Vuex 中的用户信息
					await this.$store.dispatch('UpdateInfo', userData.data);
					// 报名
					await activityApi.getTouristJoin(params);
					uni.redirectTo({
						url: `/brisk-walking/detail?title=${this.options.title}&id=${this.options.id}`
					})
				}catch(error){
					console.log('报名失败：',error);
					errorToast(error);
				}
			},			
			//h5页面初始化表单信息
			async initFormData(){
				// #ifdef H5
				const app = getApp();
				const currentUser = app.globalData.currentUser;
				let phone = currentUser.memberPhone;
				let unionId = currentUser.unionid;
				const userRs = await loginApi.getUserInfoByUnionId({memberPhone:phone,unionId:unionId});
				if(userRs.data.orgId){
					this.userInfo.realName = userRs.data.realName;
					this.userInfo.orgId = userRs.data.orgId;
					this.userInfo.orgName = userRs.data.orgName;
					this.userInfo.mobile = phone;
					this.userInfo.memberId = userRs.data.memberId;
				}else{
					this.userInfo.mobile = userRs.data.mobile;
					this.userInfo.memberId = userRs.data.memberId;
				}
				await this.login({unionId:userRs.data.unionId,memberPhone:userRs.data.mobile});
				this.isH5 = true;
				// #endif
			},
			async changeCountDown(e) {
				if (e.seconds == 0) {
					if(!this.userInfo.orgId){
						await this.initFormData();
					}
					this.show = true
				}
			},
			async getPhoneNumber(e){
				if(e.detail.errMsg === 'getPhoneNumber:ok'){
					const { code } = e.detail;
					const loginCode = await wxLogin();
					//通过code获取用户的手机号
					const result = await loginApi.getUserInfoByCode({authPhoneCode:code,loginCode:loginCode});
					if(result.data.orgId){
						this.userInfo.mobile = result.data.mobile;
						this.userInfo.realName = result.data.realName;
						this.userInfo.orgId = result.data.orgId;
						this.userInfo.orgName = result.data.orgName;
						this.userInfo.memberId = result.data.memberId;
					}else{
						this.userInfo.mobile = result.data.mobile;
						this.userInfo.memberId = result.data.memberId;
					}
					
					await this.login({unionId:result.data.unionId,memberPhone:result.data.mobile});
				}else {
					uni.showToast({
					  title: '你拒绝了授权,无法获取手机号',icon: 'error'
					});
				}
			},
			async login(formData){
				uni.showLoading({ title: '登录中' });
				try {
				    const res = await this.$store.dispatch('LoginByUnionId', formData);
				    await this.$store.dispatch('GetInfo');
				    uni.hideLoading();
				} catch (error) {
				    uni.hideLoading(); 
				    uni.showToast({
				      icon: 'none',title: error.message || '登录失败',duration: 3000
				    });
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	
.countdown {
	padding: 10rpx 30rpx;
	border-radius: 40rpx;
	position: absolute;
	top: 20rpx;
	right: 20rpx;
	background-color: rgba(0, 0, 0, 0.3);
	
	:deep(text) {
		color: #fff;
	}
}

.form {
	background-image: url(https://chqyoss.leijue.net/pic/pic5.jpg );
	background-repeat: no-repeat;
	background-size: 100% 100%;
	padding: 120rpx 120rpx 200rpx;
	width: 100%;
	
	.item-label {
		padding: 30rpx 0 10rpx;
	}
}

.signup {
	background-image: url('@/static/images/icon/activity/walking/btn.jpg');
	background-repeat: no-repeat;
	background-size: 100% 100%;
	height: 100px;
	display: flex;
	justify-content: center;
	align-items: center;
	color: #fff;
	font-size: 40rpx;
}

.op-wrap {
	position: absolute;
	top: 50vh;
	bottom: 0;
	left: 0;
	right: 0;
	
	display: flex;
	justify-content: center;
	align-items: center;
	
	.u-button {
		width: 300rpx;
	}
}

:deep(.u-popup__content) {
	background-color: transparent !important;
	.u-modal {
		// height: 80vh;
		
		.u-modal__content {
			padding: 0;
		}
	}
}
:deep(.u-action-sheet) {
	background-color: #fff;
}
.phone-input {
	background-color: #D8D8D9;
}
.phone-btn {
	background-color: red;width: 70px;height: 30px;line-height: 30px;color :#fff;
	position: absolute;
	right: 65px;
	border-radius: 10px;
	z-index: 999999999;
}
</style>
